package com.jeeplus.modules.web.service;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.persistence.DataEntity;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.web.entity.YjUserRoomQrcode;
import com.jeeplus.modules.web.mapper.YjUserRoomQrcodeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 微信用户-棋牌室房间二维码Service
 * @author liangbing
 * @version 2021-03-11
 */
@Service
@Transactional(readOnly = true)
public class YjUserRoomQrcodeService extends CrudService<YjUserRoomQrcodeMapper, YjUserRoomQrcode> {

    @Autowired
    private YjUserRoomQrcodeMapper yjUserRoomQrcodeMapper;

    public YjUserRoomQrcode get(String id) {
        return super.get(id);
    }

    public YjUserRoomQrcode getByRoomQrcode(String roomQrcode) {
        return yjUserRoomQrcodeMapper.getByRoomQrcode(roomQrcode, DataEntity.DEL_FLAG_NORMAL);
    }

    public YjUserRoomQrcode getByOpenid(String openid) {

        // 获得设置的有效小时数
        int activeHours = 8; //默认有效时间为8小时
        String roomQrcodeActivateHours = Global.getConfig("roomQrcodeActivateHours");// 房间二维码有效小时数
        if (StringUtils.isNotBlank(roomQrcodeActivateHours)) {
            activeHours = Integer.parseInt(roomQrcodeActivateHours);
        }

        int minutes = activeHours * 60;

        return yjUserRoomQrcodeMapper.getByOpenid(openid, minutes, DataEntity.DEL_FLAG_NORMAL);
    }

    public List<YjUserRoomQrcode> findList(YjUserRoomQrcode yjUserRoomQrcode) {
        return super.findList(yjUserRoomQrcode);
    }

    public Page<YjUserRoomQrcode> findPage(Page<YjUserRoomQrcode> page, YjUserRoomQrcode yjUserRoomQrcode) {
        return super.findPage(page, yjUserRoomQrcode);
    }

    public Long count(YjUserRoomQrcode yjUserRoomQrcode) {
        return super.count(yjUserRoomQrcode);
    }

    @Transactional(readOnly = false)
    public void save(YjUserRoomQrcode yjUserRoomQrcode) {
        super.save(yjUserRoomQrcode);
    }

    @Transactional(readOnly = false)
    public void insertOrUpdate(YjUserRoomQrcode yjUserRoomQrcode) {

        // 判断是否已经存在
        YjUserRoomQrcode record = new YjUserRoomQrcode();
        record.setOpenid(yjUserRoomQrcode.getOpenid());
        
        YjUserRoomQrcode dbRecord = yjUserRoomQrcodeMapper.findFirst(record);
        if (dbRecord != null) {
            yjUserRoomQrcode.setId(dbRecord.getId());
            yjUserRoomQrcodeMapper.update(yjUserRoomQrcode);
        } else {
            yjUserRoomQrcodeMapper.insert(yjUserRoomQrcode);
        }
    }


    @Transactional(readOnly = false)
    public void delete(YjUserRoomQrcode yjUserRoomQrcode) {
        super.delete(yjUserRoomQrcode);
    }
}
